//经销商业务机会 阶段变更 
/*
"经销商渠道建设的业务机会增加按钮”升迁到下一阶段“：
1、当阶段为意向时，点击升迁到下一阶段，弹出经销商经营产品和主要用户的开发界面，若未填下不能点击下一步，若已填写核对后点击下一步，判断是否有报价状态为""申请中""或""已批准""或“已拒绝”的或者销售政策状态为“审批中”或“已批准”或“已拒绝”的，若有阶段自动变更为方案谈判，若无提示新建报价或者销售政策，销售政策的仪器只能从意向产品选择；
2、当阶段为方案谈判时，新建合同，且合同状态为“已生效”时，阶段变更为合同签订，锁定该业务机会；
3、除合同签订阶段外，其他阶段均可选择丢单，丢单时验证是否填写丢单原因和丢单原因说明，锁定该业务机会。"

*/
public without sharing class DealerOppController {

	public String backId {private set; get;}

	public Boolean isErr  {private set; get;}
	public String msg  {get;set;}
	public Boolean isSuccess {private set; get;}

	public String detailsJson {private set; get;}
	public String searchJson {get;set;}
	public String dataJson {get;private set;}
	public String saveJson {get;set;}


	public String useMKProductscombox  {private set; get;}
	public String agentMKProductLinecombox  {private set; get;}
	public String agentGradecombox  {private set; get;}
	public String agentScalecombox  {private set; get;}
	public String agentProductLinecombox  {private set; get;}
	public String coopmodecombox  {private set; get;}

	public String recordTypeCombobox {private set;get;}
	public String systemCombobox {private set;get;}

    public String lostReasonCombobox {private set; get;}
	private Opportunity opp ; 

	public String stageName  {private set; get;}

	public Boolean isOpp  {private set; get;}

    public Boolean drop  {private set; get;}
	public class ControllerException extends Exception {}
    public String newContractURL {private set;get;}

    public DealerOppController() {
        backId = System.currentPageReference().getParameters().get('id');
        String d  = System.currentPageReference().getParameters().get('drop');
        drop = d != null; 
        isOpp = false;

    }

    private void getCombox(){

    	useMKProductscombox = getOptMap(ImportObject.getPicklistValues('MajorUserInfo__c', 'MaccuraProductInUse__c', false),true);
    	agentMKProductLinecombox  = getOptMap(ImportObject.getPicklistValues('Account', 'MaccuraProductLines__c', false),true);
    	coopmodecombox  = getOptMap(ImportObject.getPicklistValues('MajorUserInfo__c', 'CooperationMode__c', false),false);
    	agentProductLinecombox =EncodingUtil.urlEncode(JSON.serialize(ImportObject.getPicklistValues('DealerManageProduct__c', 'ProductLine__c', false).keySet()), 'UTF-8')  ;
    	agentGradecombox = getOptMap(ImportObject.getPicklistValues('DealerManageProduct__c', 'ProxyGrade__c', false),false);

    	agentScalecombox = getOptMap(ImportObject.getPicklistValues('DealerManageProduct__c', 'ProxyScale__c', false),true);
    	systemCombobox = getOptMap(ImportObject.getPicklistValues('Account', 'System__c', false),false);
    	recordTypeCombobox = getRecordOpts();
        

    }

    
    private String getRecordOpts( ){

      Map<String,String> tmpMap = new Map<String,String>();

        for (RecordType r   :Database.query('select Name  from RecordType where  SObjectType=\'Account\' ' ) ){
            tmpMap.put(r.Name , r.Name );
        }
        return getOptMap(tmpMap,false);
    }
    private String getOptMap(Map<String,String> opts, Boolean ismulti ){
       	Map<String ,Object> cooMap = new Map<String ,Object> ();
      	cooMap.put('valueField', 'value');
      	cooMap.put('textField', 'label');
      	cooMap.put('panelHeight', 'auto');
      	cooMap.put('limitToList', 'true');
        cooMap.put('separator', ';');
      	if(ismulti)cooMap.put('multiple', 'true');

      	List<Map<String,String>>  dList = new List<Map<String,String>>();
      	for (String k : opts.keySet()) {
	        Map<String ,String> dataMap = new Map<String,String>();
	        dataMap.put('label',opts.get(k) );
	        dataMap.put('value',k );
	        dList.add(dataMap);
      	}  
      	cooMap.put('data', dList);   
      
      	return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');
    }

    public void init (){

    	try {

            System.debug('DealerOppController==>'+backId);
    		if(backId == null)setErr('页面打开错误!');

    		if(Id.valueOf(backId).getSObjectType() == Opportunity.SObjectType){//业务机会 阶段变更

    			opp = [select Id , WinRatio__c,AccountId,StageName,LostReason__c,LostReasoneDesc__c,RecordType.Name from Opportunity where Id=:backId];
    			stageName = opp.StageName ; 
                newContractURL = '/flow/NewContract?OppID='+opp.Id+'&AccountID='+opp.AccountId+'&Stage='+opp.StageName+'&RecordType='+opp.RecordType.Name;

    			getDetails(opp.AccountId);
    			isOpp = true ;
                lostReasonCombobox = getOptMap(ImportObject.getPicklistValues('Opportunity', 'LostReason__c', false),false);
                if(opp.StageName == '失败' ) setErr('业务机会已丢单,不能操作!');



                 if(drop && opp.StageName == '合同签订' ) setErr('业务机会已赢单,不能操作!');

                if(drop) return;
               
               if(  opp.StageName == '意向'
                    && [select count()  from Quote where Status in ('申请中','已批准','已拒绝') and  OpportunityId=:backId] == 0 
                    && [select count() from InstrumentPolicy__c where Status__c in ('审批中','已批准','已拒绝') and  Opportunity__c=:backId ] == 0 
                    && [select count() from Measure_Calculate__c where Status__c in ('已提交' ,'审批拒绝' , '审批成功') and  Opportunity__c=:backId ] == 0 

                    && [select count() from BloodSugarOrder__c where Opportunities__c =:backId and Status__c in ('审批中','审批拒绝','审批成功')]  == 0 

                )setErr('1)没有已提交的报价/仪器政策/测算/血糖仪配送申请不能升迁到下一阶段! 2)若有仪器意向,请先添加意向产品!');

                if(opp.StageName == '方案谈判' ){
                    
                    if([select count() from ContractProduct__c where Opportunity__c =:backId ] ==0 ){
                        setErr('待报价/仪器政策/测算/血糖仪配送申请批准后，请点击”添加合作明细“!');
                    }else{
                        setErr('渠道建设业务机会当全部的合作仪器明细和合作试剂明细关联的合同均已生效（即OA合同流程归档）时，渠道建设业务机会自动升迁合同签订阶段。');
                    }

                }
                if(opp.StageName == '合同签订' )setErr('业务机会已完结!');

            
    		}else if(Id.valueOf(backId).getSObjectType() == Account.SObjectType){//经销商 信息完善
    			opp = new Opportunity();
                getDetails(backId);

    		}
    		getCombox();
    	    
    	}catch (Exception e) {
    		ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
    	}
    }


     ///检索客户
    public void search (){

    	Map<String ,Object > searchMap = (Map<String ,Object >) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));

    	AccountBean ab = new AccountBean(searchMap);

    	String sql = ' select Id ,Name,TureProvince__r.Name ,Province__r.Name,'+
    	'  City__r.Name ,District__r.Name  , DirectSale__c , Owner.Name , System__c ,Area__c , '+
    	' AccountNumber ,Country__r.Name  , RecordType.Name,Country__r.Area1__c,Country__r.Area2__c ' +
    	'  from Account   where AccountNumber != \'JKDYKH\'  and Name !=\'迈克测试\'  and RecordType.Name like \'%终端%\' ';

    	if(ab.accName != null && ab.accName != '')sql += ' and Name like \'%'+ab.accName+'%\' ';
    	if(ab.accountNumber != null && ab.accountNumber != '')sql += ' and accountNumber = \''+ab.accountNumber+'\' ';
    	if(ab.country != null && ab.country != '')sql += ' and Country__r.Name like \'%'+ab.country+'%\' ';
    	if(ab.province != null && ab.province != '')sql += ' and Province__r.Name like \'%'+ab.province+'%\' ';
    	if(ab.city != null && ab.city != '')sql += ' and City__r.Name  like \'%'+ab.city+'%\' ';
    	if(ab.district != null && ab.district != '')sql += ' and District__r.Name like \'%'+ab.district+'%\' ';
    	if(ab.thridSystem != null && ab.thridSystem != '')sql += ' and ParentId != null  and  System__c like \'%'+ab.thridSystem+'%\' ';
    	if(ab.recordtype != null && ab.recordtype != '')sql += ' and RecordType.Name = \''+ab.recordtype+'\' ';
    	

    	sql += ' limit 200 ';
    
    	//
    	List<AccountBean> tmp = new List<AccountBean>();
    	for (Account acc : Database.query(sql)) {
    		tmp.add(new AccountBean(acc));
    	}
    	dataJson  = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');
    }

 


    //验证业务机会是否可以进入下一阶段
   /* public Boolean checkNext(String oppid){

    	Opportunity opp = [select Id,StageName,AccountId,Account.MaccuraProductLines__c,Account.RegisterAmount__c,
    	Account.MainManager__c,Account.SalesmanNo__c
    	 from Opportunity where Id=:oppid];
    	if(opp.StageName == '意向'){

    		if(opp.Account.MaccuraProductLines__c == null )return false; 

    	 	if(opp.Account.RegisterAmount__c == null )return false; 

    	 	if(opp.Account.MainManager__c == null )return false;

    	 	if(opp.Account.SalesmanNo__c == null) return false;

    		if([select count() from MajorUserInfo__c where Dealer__c =:opp.AccountId ] == 0)return false; 
    		if([select count() from DealerManageProduct__c where Dealer__c =:opp.AccountId ] == 0)return false;

    		if([select count()  from Quote where Status in ('申请中','已批准','已拒绝') ] == 0 
    			&& [select count() from InstrumentPolicy__c where Status__c in ('申请中','已批准','已拒绝') ] == 0 )return false;

    	}else if(opp.StageName == '方案谈判'){

    		if([select count() from Contract__c where Opportunity__c=:opp.Id and Status__c ='已生效'] == 0) return false;

    	}
    	 

    	return true; 
    	
    }
    */


    public void save(){


    	Map<String,Object> resMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
    	if(drop){
            SavePoint sp1 = Database.setSavepoint();
            try {
                opp.StageName = '失败';
                opp.LostReasoneDesc__c = String.valueOf(resMap.get('dropReasonNote'));
                opp.LostReason__c = String.valueOf(resMap.get('dropReason'));
                update opp;
                msg = '业务机会已丢单!';
                isSuccess = true ;
            }catch(Exception e ){
                msg ='操作失败!' +e.getMessage()+e.getStackTraceString();
                Database.rollback(sp1);

            }

            return;
        }
        Account acc = new Account();
    	if(resMap.containsKey('Dealer')){//经销商主要信息
    		Map<String,Object>  accm  = (Map<String,Object> )resMap.get('Dealer');
    		acc.Id =  DataUtil.getStringValue(accm.get('accId'));
    		acc.RegisterAmount__c = DataUtil.getDecimalValue(accm.get('registerAmount'));
    		acc.SalesmanNo__c = DataUtil.getDecimalValue(accm.get('salercount'));
    		acc.MainManager__c = DataUtil.getStringValue(accm.get('mainperson'));
    		acc.MaccuraProductLines__c = DataUtil.getStringValue(accm.get('agentProductLine'));
    		opp.WinRatio__c = DataUtil.getDecimalValue(accm.get('winrito'));
    	}
    	System.debug(acc);
        System.debug(resMap.get('Account'));
    	List<MajorUserInfo__c> muList = new List<MajorUserInfo__c>();
        
        Set<Id>details = new Set<Id>();

    	if(resMap.containsKey('Account')){//经销商主要客户
    		for (Object o:(List<Object>) resMap.get('Account') ) {
    			Map<String,Object> mo = (Map<String,Object>)o;
	    		MajorUserInfo__c mu = new MajorUserInfo__c();
	    		mu.MajorCustomer__c = DataUtil.getStringValue(mo.get('accId'));
	    		mu.MaccuraProductInUse__c = DataUtil.getStringValue(mo.get('useMKProducts'));
	    		mu.CooperationMode__c = DataUtil.getStringValue(mo.get('coopmode'));
	    		mu.Remark__c = DataUtil.getStringValue(mo.get('remark'));
	    		mu.Dealer__c = acc.Id; 
	    		muList.add(mu);
                String dId = DataUtil.getStringValue(mo.get('detailId'));
                mu.Id = dId; 

                if(String.isNotBlank(dId))details.add(dId);
	    	}
    	}
    	List<DealerManageProduct__c> dpList = new List<DealerManageProduct__c>();
    	if(resMap.containsKey('Product')){//经销商代理产品
    		for (Object o:(List<Object>) resMap.get('Product') ) {
    			Map<String,Object> mo = (Map<String,Object>)o;
    			DealerManageProduct__c mu = new DealerManageProduct__c();
	    		mu.ProductLine__c = DataUtil.getStringValue(mo.get('agentProductLine'));
	    		mu.Brand__c = DataUtil.getStringValue(mo.get('agentBrandId'));
	    		mu.LastYearSalesAmount__c = DataUtil.getDecimalValue(mo.get('lastAmount'));
	    		mu.ProxyGrade__c = DataUtil.getStringValue(mo.get('agentGrade'));
	    		mu.ProxyScale__c = DataUtil.getStringValue(mo.get('agentScale'));
	    		mu.AgentArea1__c = DataUtil.getStringValue(mo.get('agentArea'));
	    		mu.SalesPolicy__c = DataUtil.getStringValue(mo.get('policy'));
	    		mu.Remark__c = DataUtil.getStringValue(mo.get('remark'));
	    		mu.Dealer__c = acc.Id; 
	    		dpList.add(mu);
    		}

    	}

    	SavePoint sp = Database.setSavepoint();
    	try {
    	  	 
    	  	update acc ;
    	  	Delete [select Id from DealerManageProduct__c where Dealer__c =:acc.Id];

    	  	Delete [select Id from MajorUserInfo__c where Dealer__c =:acc.Id and BackgroundImport__c != true and Id not in: details   ];

    	  	if(muList.size() > 0) upsert  muList;
    	  	if(dpList.size() > 0) insert dpList;  
    	  	if(isOpp && opp.StageName == '意向'){
    	  		opp.StageName = '方案谈判';
    	  		
    	  	}
            if(isOpp == true )update opp;
    	  	isSuccess = true;
    	  	msg =  isOpp ? '已成功升迁到方案谈判!' :'保存成功!';
            msg = '保存成功!';
    	}catch (Exception e) {
    	    Database.rollback(sp);
    	    msg = '操作失败:'+e.getMessage();

    	}
    	

    }



    //获取 信息
    private void getDetails(String accId ){
    	
    	Map<String , Object> resMap = new Map<String ,Object>();
    	
    	if(accId != null){

    		//1.获取经销商信息
    		Account acc  = [select Id,RegisterAmount__c ,MaccuraProductLines__c ,
    		MainManager__c, SalesmanNo__c 
    		from Account where Id=:accId ];
            System.debug('DealerOppController==>'+acc);
    		resMap.put('Dealer',new DealerBean(acc,opp ));
    		//2.获取 主要客户信息
    		List<AccountBean> atmp = new List<AccountBean>();
    		for(MajorUserInfo__c mu :[select Id ,BackgroundImport__c,MajorCustomer__c, MajorCustomer__r.Name, 
    		 MaccuraProductInUse__c,CooperationMode__c,Remark__c 
    			from MajorUserInfo__c where Dealer__c =:accId ]){
    			atmp.add(new AccountBean(mu));
    		}
    		resMap.put('Account',atmp);
    		//3获取 主要经营产品信息
    		List<DealerProductBean> dtmp = new List<DealerProductBean>();
    		for(DealerManageProduct__c dmp : [select Id,ProductLine__c, Brand__c, LastYearSalesAmount__c, 
    			ProxyGrade__c,ProxyScale__c,AgentArea1__c,SalesPolicy__c, Remark__c,Brand__r.Name 
    			from DealerManageProduct__c where Dealer__c =:accId]){
    			dtmp.add(new DealerProductBean(dmp));
    		}
    		resMap.put('Product', dtmp);
    	}
        if(drop){
            Map<String,String> dropMap = new Map<String,String>();
            dropMap.put('dropReason', opp.LostReason__c);
            dropMap.put('dropReasonNote', opp.LostReasoneDesc__c);
            resMap.put('Opportunity',dropMap ); 
        }
       

    	detailsJson = EncodingUtil.urlEncode(JSON.serialize(resMap), 'UTF-8');

    }
    private void setErr(String message){
        System.debug('Err==>'+message);
    	isErr  =true;
    	throw new ControllerException(message);
    }

    public  void setNil() {
    	detailsJson = '{}';
    	dataJson = '[]';
    	searchJson = '{}';
    	saveJson = '{}';
    }
     public class  DealerBean{
    	public String accId ; 
    	public String agentProductLine; //代理 产品线
    	public Decimal registerAmount ;//注册资金
    	public Decimal salercount ; //销售员数量
    	public String  mainperson ;//负责人
        public Decimal winrito  ; //赢单率
    	public DealerBean(Account acc ,Opportunity opp ){
    		accId = acc.Id ; 
    		registerAmount = acc.RegisterAmount__c;
    		salercount = acc.SalesmanNo__c;
    		mainperson = acc.MainManager__c;
            System.debug('DealerOppController==>'+acc);
    		agentProductLine = acc.MaccuraProductLines__c; 
            winrito = opp.WinRatio__c;
    	}
    }

    public  class AccountBean {

    	public String accId ; 
        public String detailId ; 

    	public String accName ; 
    	public String useMKProducts ; 
    	public String coopmode ; 
    	public String remark ; 

    	public String accountNumber;
    	public String country;
    	public String province;
    	public String city;
    	public String district;
    	public String thridSystem ;
    	public String recordtype ;
    	public String area; 
        public boolean backImport;
        

    	public AccountBean(MajorUserInfo__c acc  ){

    		accId = acc.MajorCustomer__c; 
    		accName = acc.MajorCustomer__r.Name ;

    		useMKProducts = acc.MaccuraProductInUse__c;
    		coopmode = acc.CooperationMode__c;
    		remark = acc.Remark__c;
            backImport = acc.BackgroundImport__c;
            detailId = acc.Id ; 

    	}
    	public AccountBean(Account acc ){
    		accId = acc.Id ; 
    		accName = acc.Name ;

    		accountNumber = acc.AccountNumber ; 

    		country = acc.Country__r.Name;
    		province = acc.Province__r.Name;

    		city = acc.City__r.Name; 
    		district = acc.District__r.Name;


    		thridSystem = acc.System__c ; 
    		recordtype = acc.RecordType.Name; 
    
    		area = acc.Area__c; 
    	}

    	public AccountBean(Map<String,Object> o ){

    		accName = getStringValue(o.get('accName'));
    		accId = getStringValue(o.get('accid'));
    		accountNumber = getStringValue(o.get('accountNumber'));
    		country = getStringValue(o.get('country'));
    		province = getStringValue(o.get('province'));
    		city = getStringValue(o.get('city'));
    		district = getStringValue(o.get('district'));
    		thridSystem = getStringValue(o.get('thridSystem'));
    		recordtype = getStringValue(o.get('recordtype'));
    		area = getStringValue(o.get('area'));

    	}
    	private String getStringValue(Object o ){
    		if(o == null) return null ; 
    		return String.valueOf(o).trim();
    	
    	}
    }
    public class DealerProductBean{
    	public String agentProductLine;
    	public String agentBrand ; 
    	public Decimal lastAmount ; 
    	public String agentGrade; 
    	public String agentScale; 
    	public String agentArea ; 
        public String agentBrandId; 
    	public String policy ; 
    	public String remark ; 
    	public DealerProductBean(DealerManageProduct__c dmp ){
    		agentProductLine = dmp.ProductLine__c;
    		agentBrand = dmp.Brand__r.Name;
            agentBrandId = dmp.Brand__c;
    		lastAmount = dmp.LastYearSalesAmount__c;
    		agentGrade = dmp.ProxyGrade__c;
    		agentScale = dmp.ProxyScale__c;
    		agentArea = dmp.AgentArea1__c;

    		policy = dmp.SalesPolicy__c;
    		remark = dmp.Remark__c;
    	}
    }







}